const config = require('config');

let amazonUtils = {};

const {OperationHelper} = require('apac');

let opHelper = new OperationHelper({
    awsId: config.aws.id,
    awsSecret: config.aws.secret,
    assocId: config.aws.tag,
    locale: 'CN',
    maxRequestsPerSecond: 0.5
});
amazonUtils.formatBook = amazonBook => {
    if (!amazonBook) {
        return null;
    }
    let result = {};
    result.isbn13 = amazonBook.ItemAttributes.ISBN || amazonBook.ItemAttributes.EAN;
    result.title = amazonBook.ItemAttributes.Title;
    result.author = [amazonBook.ItemAttributes.Author];
    result.publisher = amazonBook.ItemAttributes.Publisher;
    result.price = amazonBook.ItemAttributes['ListPrice'] ? amazonBook.ItemAttributes['ListPrice']['Amount'] / 100 + '' : null;
    result.image = amazonBook.MediumImage.URL;
    result.summary = amazonBook.EditorialReviews &&
        amazonBook.EditorialReviews.EditorialReview.Content;
    result.binding = amazonBook.ItemAttributes.Binding; // 包装
    result.pages = amazonBook.ItemAttributes.NumberOfPages; // 页数
    result.pubdate = amazonBook.ItemAttributes.PublicationDate; // 页数
    result.awsUrl = amazonBook.DetailPageURL; // 亚马逊页面 URL
    result.images = {
        small: amazonBook.SmallImage.URL,
        large: amazonBook.MediumImage.URL,
        medium: amazonBook.LargeImage.URL
    };
    return result;
};
amazonUtils.queryBook = ISBN => {
    return opHelper.execute('ItemLookup', {
        ItemId: ISBN,
        IdType: 'ISBN',
        ResponseGroup: 'Images,ItemAttributes,EditorialReview',
        SearchIndex: 'Books'
    }).then(response => {
        if (response.result.ItemLookupErrorResponse) {
            return Promise.reject(response.result.ItemLookupErrorResponse.Error);
        }
        // console.log('Amazon response:', JSON.stringify(response.result));
        let res = response.result['ItemLookupResponse']['Items']['Item'];
        if (res instanceof Array) {
            res = res[0];
        }
        return amazonUtils.formatBook(res);
    });
};


module.exports = amazonUtils;
